<?php

namespace App\Http\Controllers\home;

use App\user_infos;
use Validator;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class loginController extends Controller
{
    public function index(Request $request)
    {
        if ($request->session()->get('username')) {
            return redirect('/');
        }
        return view('home\login');
    }

    public function login(Request $request)
    {
        $messages = [
            'user.required' => '您没有填写 用户名',
            'pwd.required' => '您没有填写 密码'
        ];

        $rules = [
            'user' => 'required',
            'pwd' => 'required'
        ];

        $validator = Validator::make($_REQUEST, $rules, $messages);
        $validator->validate();

        $username = $request->input('user');
        $password = $request->input('pwd');

        $user = User::where('user', $username)->first();
        $SpAID = user_infos::where("IID",$user->UID)->first()->SpAID;
        if ($user != null) {
            if ($password === $user->pwd) {
                $request->session()->put('username', $username);
                $request->session()->put('UID', $user->UID);
                $request->session()->put('GID', $user->GID);
                $request->session()->put('SpAID', $SpAID);
                cookie("username",$username,1);
                return "true";
            } else {
                $validator->errors()->add('pwd', '密码错误！');
                return '密码错误！';
            }
        } else {
            $validator->errors()->add('user', '用户不存在！');
            return '用户不存在！';
        }
    }

    public function logout(Request $request)
    {
        $request->session()->pull('username', 'default');
        return redirect('/');
    }

}
